import React, {Component} from 'react';
import {
	AppRegistry,
	Dimensions,
	Platform,
	NativeModules,
	DeviceInfo,
	StyleSheet,
	Image,
	Text,
	View,
	TextInput,
	PixelRatio,
	TouchableOpacity,
	ScrollView,
	AsyncStorage,
  DeviceEventEmitter
} from 'react-native';

var Common = require('./common');
import ImagePicker from 'react-native-image-picker';

const pixelRatio = PixelRatio.get();
const dismissKeyboard = require('dismissKeyboard');
const options = {
	title: '选择图片',
	cancelButtonTitle: '取消',
	takePhotoButtonTitle: '拍照',
	chooseFromLibraryButtonTitle: '图片库',
	cameraType: 'back',
	mediaType: 'photo',
	videoQuality: 'high',
	durationLimit: 10,
	maxWidth: 600,
	maxHeight: 600,
	aspectX: 2,
	aspectY: 1,
	quality: 0.8,
	angle: 0,
	allowsEditing: false,
	noData: false,
	storageOptions: {
		skipBackup: true,
		path: 'images'
	}
};
export default class MyProfile extends Component<Props> {
	static navigationOptions = {
		headerTitle: '个人资料',
		tabBarLabel: '个人资料',

	};

	constructor(props) {
		super(props);
		this.state = {
			userinfo: {avatar: {}}
		};
	}

	login() {
		var _this = this;
		Common.ajaxPost(Common.url + 'login.php', function (res) {
			if (res.code == "0000") {

			}
		}.bind(this), {verify: '08login', t: ''}, this.props);
	}

	toRegister() {
		this.props.navigation.navigate('Register')
	}

	toEditInput(str) {
		this.props.navigation.navigate('EditInput', str)
	}

	getData() {
		var _this = this;
		var config = {
			method: 'GET',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'multipart/form-data',
				'credentials': 'include',
				'Cookie': _this.state.cookie
			},
			credentials: 'include',

		}


		fetch(Common.url + 'thinksns/index.php?app=public&mod=Account&act=index&is_ajax=1', config).then((response) => response.json()).then((res) => {
			console.log(res)
			if (res.status == 1) {
				_this.setState({
					userinfo: res.data
				})

			}
		})
	}

	showImagePicker() {
		var _this = this;
		ImagePicker.showImagePicker(options, (response) => {
			if (response.didCancel) {
				console.log('User cancelled image picker');
			}
			else if (response.error) {
				console.log('ImagePicker Error: ', response.error);
			}

			else {
				console.log(response)

				this.setState({
					picbox: response
				})
				let formData = new FormData();//如果需要上传多张图片,需要遍历数组,把图片的路径数组放入formData中
				let file = {uri: response.uri, type: 'multipart/form-data', name: 'image.png'};   //这里的key(uri和type和name)不能改变,
				//formData.append("files",file);   //这里的files就是后台需要的key

				formData.append("string", file);

				var config = {
					method: 'POST',
					headers: {
						'Accept': 'application/json',
						'Content-Type': 'multipart/form-data',
						'credentials': 'include'
					},
					credentials: 'include',
					body: formData,
				}


				fetch(Common.url + 'thinksns/index.php?app=public&mod=Account&act=doSaveAvatar&step=upload&is_ajax=1', config).then((response) => response.json()).then((res) => {
					console.log(res)
					if (res.status == 1) {
						console.log(res.data)


						_this.changeTouxiang(res.data.fullpicurl, res.data.picwidth)
					}
					else if(res.status == 401){
						this.props.navigation.navigate('Login');
					}
				})
			}
		});
	}

	changeTouxiang(url, picwidth) {
		var _this = this;
		var userinfo = _this.state.userinfo;
		userinfo.avatar_original = url;
		_this.setState({
			userinfo: userinfo
		})
		var config = {
			method: 'POST',
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				'credentials': 'include',
				'Cookie': _this.state.cookie
			},
			credentials: 'include'
		}
		var param = {
			picurl: url,
			picwidth: picwidth,
			fullpicurl: null,
			x1: 0,
			y1: 0,
			x2: 200,
			y2: 200,
			w: 200,
			h: 200
		}
		if (param) {
			config["body"] = JSON.stringify(param);
		}

		fetch(Common.url + 'thinksns/index.php?app=public&mod=Account&act=doSaveAvatar&step=save&is_ajax=1', config).then((response) => response.json()).then((res) => {
			console.log(res)
		})
	}

	componentDidMount() {
		// AsyncStorage.getItem('logindata').then((value)=>{
		// 	console.log(JSON.parse(value))
		//   var userinfo = JSON.parse(value)
		// 	this.setState({
		// 		userinfo:userinfo,
		//     photoUrl: userinfo.avatar.avatar_original
		// 	})
		// })
		AsyncStorage.getItem('cookie').then((value) => {
			console.log(value)
			this.setState({
				cookie: value
			}, () => {
				this.getData()
			})
		})

    this.listener1 = DeviceEventEmitter.addListener('realname', (value)=>{
      let userinfo = this.state.userinfo;
       userinfo.uname = value;
       this.setState({
         userinfo: userinfo
       })
    });
    this.listener2 = DeviceEventEmitter.addListener('idcard', (value)=>{
      let userinfo = this.state.userinfo;
       userinfo.idcard = value;
       this.setState({
         userinfo: userinfo
       })
    });
    this.listener3 = DeviceEventEmitter.addListener('companyname', (value)=>{
      let userinfo = this.state.userinfo;
       userinfo.companyname = value;
       this.setState({
         userinfo: userinfo
       })
    });
    this.listener4 = DeviceEventEmitter.addListener('address', (value)=>{
      let userinfo = this.state.userinfo;
       userinfo.company_address = value;
       this.setState({
         userinfo: userinfo
       })
    });
    this.listener5 = DeviceEventEmitter.addListener('mobile', (value)=>{
      let userinfo = this.state.userinfo;
       userinfo.mobile = value;
       this.setState({
         userinfo: userinfo
       })
    });
    this.listener6 = DeviceEventEmitter.addListener('weixin', (value)=>{
      let userinfo = this.state.userinfo;
       userinfo.weixin = value;
       this.setState({
         userinfo: userinfo
       })
    });

		// console.log(this.props.navigation.state.params)
		// if(this.props.navigation.state.params.from){
		//   this.setState({
		//     from:this.props.navigation.state.params,
		//   })
		// }
	}
  componentWillUnmount(){
    this.listener1.remove();
    this.listener2.remove();
    this.listener3.remove();
    this.listener4.remove();
    this.listener5.remove();
    this.listener6.remove();
  }
	render() {
		const {navigate} = this.props.navigation;
		return (
			<View style={styles.container}>
				<TouchableOpacity style={styles.mineTop} onPress={this.showImagePicker.bind(this)}>
					<Text style={{fontSize: 18, color: 'rgb(33,33,33)'}}>头像</Text>
					<View style={styles.mineinner}>
						<Image style={{width: 52, height: 52, marginRight: 18, borderRadius: 26,}}
						       source={{uri: this.state.userinfo.avatar_original}}/>
						<Image style={{width: 22, height: 22}} source={require('./images/jiantou.png')}/>
					</View>
				</TouchableOpacity>
				<TouchableOpacity style={styles.mineTop} onPress={this.toEditInput.bind(this, '姓名')}>
					<Text style={{fontSize: 18, color: 'rgb(33,33,33)'}}>姓名</Text>
					<View style={styles.mineinner}>
						<Text style={{
							marginRight: 18,
							fontSize: 18,
							color: 'rgb(121,121,121)'
						}}>{this.state.userinfo.uname ? this.state.userinfo.uname : '未填写'}</Text>
						<Image style={{width: 22, height: 22}} source={require('./images/jiantou.png')}/>
					</View>
				</TouchableOpacity>
				<TouchableOpacity style={styles.mineTop} onPress={this.toEditInput.bind(this, '身份证')}>
					<Text style={{fontSize: 18, color: 'rgb(33,33,33)'}}>身份证</Text>
					<View style={styles.mineinner}>
						<Text style={{
							marginRight: 18,
							fontSize: 18,
							color: 'rgb(121,121,121)'
						}}>{this.state.userinfo.idcard ? this.state.userinfo.idcard : '未填写'}</Text>
						<Image style={{width: 22, height: 22}} source={require('./images/jiantou.png')}/>
					</View>
				</TouchableOpacity>
				<TouchableOpacity style={styles.mineTop} onPress={this.toEditInput.bind(this, '公司名称')}>
					<Text style={{fontSize: 18, color: 'rgb(33,33,33)'}}>公司名称</Text>
					<View style={styles.mineinner}>
						<Text style={{
							marginRight: 18,
							fontSize: 18,
							color: 'rgb(121,121,121)'
						}}>{this.state.userinfo.companyname ? this.state.userinfo.companyname : '未填写'}</Text>
						<Image style={{width: 22, height: 22}} source={require('./images/jiantou.png')}/>
					</View>
				</TouchableOpacity>
				<TouchableOpacity style={[styles.mineTop, {borderBottomWidth: 0}]}
				                  onPress={this.toEditInput.bind(this, '公司地址')}>
					<Text style={{fontSize: 18, color: 'rgb(33,33,33)'}}>公司地址</Text>
					<View style={styles.mineinner}>
						<Text style={{
							marginRight: 18,
							fontSize: 18,
							color: 'rgb(121,121,121)'
						}}>{this.state.userinfo.company_address ? this.state.userinfo.company_address : '未填写'}</Text>
						<Image style={{width: 22, height: 22}} source={require('./images/jiantou.png')}/>
					</View>
				</TouchableOpacity>
				<View style={{height: 8, backgroundColor: '#f5f5f5'}}></View>
				<TouchableOpacity style={styles.mineTop} onPress={this.toEditInput.bind(this, '联系方式')}>
					<Text style={{fontSize: 18, color: 'rgb(33,33,33)'}}>联系方式</Text>
					<View style={styles.mineinner}>
						<Text style={{
							marginRight: 18,
							fontSize: 18,
							color: 'rgb(121,121,121)'
						}}>{this.state.userinfo.phone ? this.state.userinfo.phone : '未填写'}</Text>
						<Image style={{width: 22, height: 22}} source={require('./images/jiantou.png')}/>
					</View>
				</TouchableOpacity>
				<TouchableOpacity style={[styles.mineTop, {borderBottomWidth: 0}]}
				                  onPress={this.toEditInput.bind(this, '微信')}>
					<Text style={{fontSize: 18, color: 'rgb(33,33,33)'}}>微信</Text>
					<View style={styles.mineinner}>
						<Text style={{
							marginRight: 18,
							fontSize: 18,
							color: 'rgb(121,121,121)'
						}}>{this.state.userinfo.weixin ? this.state.userinfo.weixin : '未填写'}</Text>
						<Image style={{width: 22, height: 22}} source={require('./images/jiantou.png')}/>
					</View>
				</TouchableOpacity>
			</View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		height: Common.screenHeight,
		backgroundColor: '#f5f5f5',
	},
	mineTop: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		paddingLeft: 16,
		paddingRight: 25,
		height: 70,
		borderBottomColor: '#e9e9e9',
		borderBottomWidth: 1,
		backgroundColor: '#fff'
	},
	mineinner: {
		flexDirection: 'row',
		alignItems: 'center',
	},
});
